How to populate MailTo link with a form action using Javascript

Someday you might want to have a form where the submit button goes to a MailTo: link. You might want to populate the email’s To: Subject: and Body.

Here is a plunk to do it:
http://plnkr.co/edit/HWkMHhlaN5MO82wQfa0q

Here is the html and javascript:

<html>
<head>
<script>
function sendemail()
{
    var body = "First name: " + document.getElementById("fn").value + "\n";
    body +=  "Last name: " + document.getElementById("ln").value;
    var email = document.getElementById("email").value;
    var location = "mailto:" + email + "?subject=Hello world&body=" + encodeURIComponent(body);
    window.location.href = location;
}
</script>
</head>
<body>
<form action="javascript: sendemail()">
First name:<br>
<input id="fn" type="text" name="firstname">
<br>
Last name:<br>
<input id="ln" type="text" name="lastname">
<br>
Email:<br>
<input id="email" type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>

One Comment

Leave a Reply

How to post code in comments?